/**
 * 
 */
package com.app.framework.socket;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.app.framework.context.AbstractContext;
import com.app.framework.context.ActionRequest;
import com.app.framework.context.Context;
import com.app.framework.exception.ClientException;
import com.app.framework.result.RequestResult;
import com.app.framework.singleton.ActionSingletonManager;
import com.app.framework.util.ErrorCodeConstants;
import com.app.service.action.SocketAction;

/**
 * @author lisong
 * @version 2013-3-7 下午3:51:21
 */
public class SocketContext extends AbstractContext {

	private static final Logger logger = Logger.getLogger(SocketContext.class);

	private List<Packet> result = new ArrayList<Packet>();
	
	public SocketContext(SocketResponse<?> response) {
		
		super(response, Context.TRANS_PROTO_SOCKET);
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public RequestResult<List<Packet>> doExecute() throws Exception {
		
		ActionRequest request = (ActionRequest)getRequest();
		
		short actionId = request.getActionId();
		
		SocketAction action = (SocketAction) ActionSingletonManager.getInstance().getSingleton(actionId);
		
		RequestResult<List<Packet>> ret = null;
		
		if(action == null) {
			throw new ClientException("action not exist actionId:"+actionId,ErrorCodeConstants.CLIENT_ERROR_ACTION_NAME_NOT_EXIST);
		}
		
		try {
			
			action.execute(this);
			
			ret = RequestResult.success(result);
			
		}catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			ret = RequestResult.serverException(e);
			perssistenceSession.close();//不保存数据
		}finally {
			//记录行为日志
			
		}
		return ret;
	}
	
	public void sendResponse(Packet...packets) {
		for(int i=0;i<packets.length;i++) {
			result.add(packets[i]);
		}
	}
	
	public void sendResponse(List<Packet> packets) {
		result.addAll(packets);
	}
	
	public SocketResponse<?> getResponse() {
		return (SocketResponse<?>) response;
	}
	@Override
	public void close() {
		super.close();
		result.clear();
		result = null;
	}
}
